//
//  JXVolumeCtrl.m
//  JiaoX
//
//  Created by swan on 15/4/3.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  现金券

#import "JXVolumeCtrl.h"
#import "SelfDataTool.h"
#import "VolumeCell.h"
#import "VolumeEmptyView.h"
#import "VoucherListHeaderView.h"

@interface JXVolumeCtrl ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)VolumeEmptyView *emptyView;
@property(nonatomic,assign)int prodPrice;
@property(nonatomic,assign)int canUseCount;
@property(nonatomic,strong)NSMutableArray *volumeArray;
@property(nonatomic,strong)VoucherListHeaderView *headerView;
@property(nonatomic,assign)BOOL isChoice;
@property(nonatomic,assign)SourceCtrlType type;
@end

@implementation JXVolumeCtrl

+(instancetype)initWithPrice:(NSMutableArray *)volumeArray  prodPrice:(int)prodPrice isChoice:(BOOL)isChoice type:(SourceCtrlType) type{
    JXVolumeCtrl *result = [[JXVolumeCtrl alloc]init];
    result.prodPrice = prodPrice;
    result.volumeArray = volumeArray;
    result.isChoice = isChoice;
    result.type = type;
    return result;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.title = @"现金券";
    //注册验证按钮点击的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(didSearch:)name:@"voucher_search_did" object:nil];
    [self setupTabView];
    [self setupEmptyPage];
    [self setupHeaderView];
    if(_volumeArray != nil){
        [self hideEmptyView];
        _canUseCount = [self getCanUseCount];
        //显示一个headerView提示用户
        if(_canUseCount == 0){
            [_headerView setTipText:@"当前无可以使用的现金券哦~"];
        }else{
            [_headerView setTipText:@"当前展示仅为本次允许使用的现金券(点击可使用)"];
        }
        [_tableView reloadData];
    }else{
        //初始化后又修改了headerView的高度需要重新设置一下
        [_headerView hideTipView];
        [_tableView beginUpdates];
        [_tableView setTableHeaderView:_headerView];
        [_tableView endUpdates];
        //数据
        _volumeArray = [NSMutableArray array];
        [self requestData];
    }
}

//初始化顶部headerView
-(void)setupHeaderView{
    _headerView = [[VoucherListHeaderView alloc]init];
    _headerView.x = 0;
    _headerView.y = 0;
    [_tableView beginUpdates];
    [_tableView setTableHeaderView:_headerView];
    [_tableView endUpdates];
}

//初始化空页面
-(void)setupEmptyPage{
    _emptyView= [[VolumeEmptyView alloc]init];
    _emptyView.x = JXScreenW/2-_emptyView.width/2;
    _emptyView.y = JXScreenH/2-_emptyView.height/2;
    [_emptyView setHidden:YES];
    [self.view addSubview:_emptyView];
}

//初始化tabView
- (void)setupTabView
{
    _tableView = [[UITableView alloc]init];
    _tableView.frame = CGRectMake(0, 0, JXScreenW, JXScreenH);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor =[UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    //处理商品较少后面多余分割线
    [_tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, JXScreenW, 0)]];
    [_tableView setHidden:YES];
    [self.view addSubview:_tableView];
}

//请求代金券数据
-(void)requestData{
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [SelfDataTool getVolumeList:params success:^(VoucherList *result) {
        [loding hide:YES];
        [_volumeArray addObjectsFromArray:result.voucherList];
        [_tableView reloadData];

        if(result.voucherList.count > 0){
            [self hideEmptyView];
        }else{
            [self showEmptyView];
        }
    } failure:^(NSError *error) {
        [loding hide:YES];
        [self showEmptyView];
        [DialogUtils showTipsWithView:self.view String:@"加载现金券失败"];
    }];
}

//显示空页面，隐藏tabview
-(void)showEmptyView{
    [_emptyView setHidden:NO];
    [_tableView setHidden:YES];
}

//隐藏空页面，显示tabView
-(void)hideEmptyView{
    [_emptyView setHidden:YES];
    [_tableView setHidden:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(_type == ACCOUNT_TYPE)
        return [self getCanUseCount];
    else
        return _volumeArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VolumeCell *cell = [VolumeCell cellWithTableView:tableView];
    [cell setVoucher:_volumeArray[indexPath.row]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int useAmount = [_volumeArray[indexPath.row] useAmount].intValue;
    int isPast = [_volumeArray[indexPath.row] isPast];
    if(_isChoice && isPast ==0 && useAmount < _prodPrice){
        //通知携带数据返回
        Voucher *voucher =  _volumeArray[indexPath.row];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"account_voucher_notify" object:voucher];
        [self.navigationController popViewControllerAnimated:YES];
    }
    //处理cell点击效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (155/2)+JXPublicInset;
}

//获取可以使用的代金卷张数
-(int)getCanUseCount{
    int canUseCount = 0;
    NSInteger count  = _volumeArray.count;
    for (int i = 0; i < count; i++) {
        if(_isChoice && [_volumeArray[i] isPast] == 0 && [_volumeArray[i] useAmount].intValue < _prodPrice){
            canUseCount++;
        }
    }
    return canUseCount;
}

-(BOOL)shouldLogin{
    return YES;
}

-(void)didSearch:(NSNotification*)aNotification{
    NSString *voucherNumber = [aNotification object];
    if(ISBLANK(voucherNumber)){
        [DialogUtils showTipsWithView:self.view String:@"序列号不能为空"];
    }else{
        [self checkVoucherNum:voucherNumber];
    }
}

//校验代金券序列号
-(void)checkVoucherNum:(NSString*)voucherNumber{
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:voucherNumber forKey:@"voucherCode"];
    [SelfDataTool validateVoucher:(NSDictionary *)params success:^(CheckVoucherRes *result) {
        [loding hide:YES];
        [self checkvoucherResult:result];
    } failure:^(NSError *error) {
         [loding hide:YES];
        [DialogUtils showTipsWithView:self.view String:@"校验失败"];
    }];
}

-(void)checkvoucherResult:(CheckVoucherRes*)result{
    UIAlertView *alert;
    NSString *status = nil;
    NSString *tipContent = nil;
    switch (result.result) {
        case 1://校验成功
            status = @"验证成功";
            tipContent = [NSString stringWithFormat:@"%@元代金券已经添加到您的账户",result.voucher.amount];
            [_volumeArray insertObject:result.voucher atIndex:0];
            [_tableView reloadData];
            break;
        case 2://代金券不存在
            status = @"验证失败";
            tipContent = @"代金券不存在";
            break;
        case 3://代金券已被使用
            status = @"验证失败";
            tipContent = @"代金券已被使用";
            break;
        case 4://代金券已被绑定
            status = @"验证失败";
            tipContent = @"代金券已被绑定";
            break;
        default:
            break;
    }
    alert = [[UIAlertView alloc]initWithTitle:status message:tipContent delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
    [alert show];
}

-(void)dealloc{
   [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
